package com.fzq.util;

import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Slf4j
@Component
public class MinIoUtil {

    @Resource
    private MinioClient minioClient;

    /**
     * 创建桶
     * @param bucketName 桶名
     */
    public void createBucket(String bucketName) {
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
        MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();
        try {
            if (minioClient.bucketExists(bucketExistsArgs)) {
                return;
            }else {
                minioClient.makeBucket(makeBucketArgs);
            }
        } catch (Exception e) {
            log.error("创建桶失败：", e.getMessage());
            throw new RuntimeException(e);
        }
    }


    /**
     * 通过 MultipartFile ，上传文件
     *
     * @param bucketName 存储桶
     * @param file       文件
     * @param objectName 对象名（文件名）
     * @param contentType   文件类型
     */
    public ObjectWriteResponse putObject(String bucketName, MultipartFile file, String objectName, String contentType) {
        try {
            //调用创建桶的代码
            createBucket(bucketName);

            InputStream inputStream = file.getInputStream();
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .contentType(contentType)
                    .stream(inputStream, inputStream.available(), -1)
                    .build();
            return minioClient.putObject(args);
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                InvalidResponseException | IOException | NoSuchAlgorithmException |
                ServerException | XmlParserException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取⽂件外链
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     */
    public String getObjectUrl(String bucketName, String objectName) {
        GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
                .method(Method.GET)
                .bucket(bucketName)
                .object(objectName)
                .expiry(7)    // 过期时间 <=7
                .build();
        try {
            String url=minioClient.getPresignedObjectUrl(args);  //生成外链
            int index=url.indexOf("?");
            url=url.substring(0,index);

            return url;
        } catch (ErrorResponseException | InsufficientDataException | InternalException |
                InvalidResponseException | InvalidKeyException | NoSuchAlgorithmException |
                IOException | XmlParserException | ServerException e) {
            throw new RuntimeException(e);
        }
    }
}
